# @Time: 2023/9/4 15:51
# @Author: Yuanqing He
# @Email: heyuanqing007@163.com
import sys
import time

from OMF import ModuleTemp
from OMF.Tools import HttpOperator
from OMF.Tools.DocumentOperator import XMLParsers
import os


class FDSModule(ModuleTemp.ModuleTemp):
    def __init__(self, work_space_path, input_data_path):
        super().__init__()

        self.work_space = work_space_path  # 工作空间地址
        self.input_data = input_data_path  # 输入数据地址
        self.MSDD = XMLParsers.getDocument("ModelServerDescriptionDocument.xml")  # 获取描述文档信息

    def initialize(self):
        super().initialize()
        # 创建FDS模块工作空间和输入数据管理空间
        if not os.path.exists(self.work_space + "\\FDS\\output"):
            os.makedirs(self.work_space + "\\FDS\\output")  # 输出管理空间

        self.work_space = self.work_space + "\\FDS"
        # 配置输入数据
        InputData = XMLParsers.getCollectionByTagName(
            self.MSDD,
            "InputData")
        upload_url = XMLParsers.getMSDDFiledataURL(InputData[0])
        HttpOperator.upload_file(upload_url[0]['url'], self.input_data)

    def run(self):
        super().run()
        # 获取模块运行接口
        Operation = XMLParsers.getCollectionByTagName(
            self.MSDD,
            "Operation")[0]
        operation_url = XMLParsers.getElementValueByElementAndTagNam(Operation, "Url")
        # 模块运行
        HttpOperator.get(operation_url)
        # 获取模块结果数据下载接口
        OutputData = XMLParsers.getCollectionByTagName(
            self.MSDD,
            "OutputData")[0]
        down_url = XMLParsers.getElementValueByElementAndTagNam(OutputData, "Url")
        HttpOperator.download_file(down_url, self.work_space + "\\output\\result.zip")

    def finish(self, timeout):
        super().finish()
        # 设置计时时间（以秒为单位）
        countdown_seconds = timeout
        # 获取当前时间
        start_time = time.time()
        # 开始计时
        while True:
            # 计算已经经过的时间
            elapsed_time = time.time() - start_time
            # 计算剩余时间
            remaining_time = countdown_seconds - elapsed_time
            # 如果剩余时间小于等于0，结束计时
            if remaining_time <= 0:
                break
        sys.exit(1)

    def getStatus(self):
        return super().getStatus()

    def getInputDataInfo(self):
        info_list = []
        input_data = XMLParsers.getCollectionByTagName(self.MSDD, "InputData")[0]
        file_datas = XMLParsers.getCollectionByTagName(input_data, 'Filedata')
        for file_data in file_datas:
            fiel_attributes = XMLParsers.getElementAttributesByElement(file_data)
        return info_list


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    FDS = FDSModule(r"E:\models\workspace", r"E:\models\FDS\FDSDemoBack.fds")
    FDS.initialize()
    FDS.run()
    print(FDS.getStatus())
    print("ok")
